<template>
  <div class="filter-container">
    <div style="margin-left: 20px;margin-top: 10px;float: left">
      <div style="float: left">
        <el-input v-model="dataForm.demoname" size="medium" placeholder="请输入任务名称" style="width: 200px;" class="filter-item" @keyup.native="handleFilter" />
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button type="danger" size="medium" @click="batchHandle">批量删除</el-button>
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button type="success" size="medium" icon="el-icon-download" @click="exportexcel">导出</el-button>
      </div>
      <div style="float: left; margin-left: 10px;">
        <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshTable">
          刷新
        </el-button>
      </div>
    </div>
    <el-table
      border
      highlight-current-row
      :data="pageData"
      style="width: 98%;left: 1.5%;"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="job_name"
        label="任务名称"
        :show-overflow-tooltip="true"
        align="center"
        sortable
        min-width="180"
      />
      <el-table-column
        prop="executor_name"
        :show-overflow-tooltip="true"
        label="执行机/组"
        align="center"
        sortable
        min-width="120"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.executor_name !== '' ">{{ scope.row.executor_name }}</span>
          <span v-else>{{ scope.row.executor_group_name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="start_time"
        label="开始时间"
        :show-overflow-tooltip="true"
        align="center"
        sortable
        min-width="180"
      />
      <el-table-column
        prop="completed_time"
        label="结束时间"
        :show-overflow-tooltip="true"
        align="center"
        sortable
        min-width="180"
      />
      <el-table-column
        prop="creator_name"
        label="创建人"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="status"
        label="任务状态"
        align="center"
        sortable
        min-width="120"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'completed'" size="small" type="success">执行完成</el-tag>
          <el-tag v-if="scope.row.status === 'stopped'" size="small" type="danger">已停止</el-tag>
          <el-tag v-if="scope.row.status === 'wait'" size="small">等待执行</el-tag>
          <el-tag v-if="scope.row.status === 'running'" size="warning">执行中</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="case_count"
        label="总用例数"
        align="center"
        sortable
        min-width="120"
      />
      <el-table-column
        prop="case_executed_count"
        label="已执行数"
        align="center"
        sortable
        min-width="120"
      />
      <el-table-column
        prop="case_success_count"
        label="成功数"
        align="center"
        sortable
        min-width="120"
      />
      <el-table-column
        prop="case_failed_count"
        label="失败数"
        align="center"
        sortable
        min-width="120"
      />
      <el-table-column
        prop="testing_progress"
        label="测试进度"
        align="center"
        fixed="right"
        sortable
        min-width="120"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.testing_progress === 100" size="small" type="success">{{ scope.row.testing_progress }}%</el-tag>
          <el-tag v-if="scope.row.testing_progress === 0" size="small" type="danger">{{ scope.row.testing_progress }}%</el-tag>
          <el-tag v-if="scope.row.testing_progress > 0 && scope.row.testing_progress < 100" size="small">{{ scope.row.testing_progress }}%</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="200">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
          <el-button type="text" size="small" @click="summary(scope.row)">汇总信息</el-button>
          <el-button v-if="scope.row.status === 'completed'" type="text" size="small" @click="testreport(scope.row)">测试报告</el-button>
          <el-button v-if="scope.row.status === 'running'" type="text" size="small" @click="stopTask(scope.row)">中止</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="margin-left: 1.5%;">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--汇总信息-->
    <el-dialog :title="currentTaskName + '--汇总信息'" width="70%" :visible.sync="summaryvisible" @close="closesummarylog">
      <div style="float: left; margin-left:1.5%;margin-bottom: 1.5%;">
        <el-button v-if="startbutton === 1" size="small" type="primary" icon="el-icon-switch-button" @click="openrefresh">开启日志自动刷新</el-button>
        <el-button v-else type="info" icon="el-icon-switch-button" @click="closerefresh">关闭自动刷新</el-button>
      </div>
      <el-table
        border
        highlight-current-row
        :data="SummaryData"
        style="width: 100%;left: 1.5%;"
        @selection-change="selectRowHandle"
      >
        <el-table-column
          prop="testset_name"
          label="测试集"
          align="center"
          sortable
          min-width="180"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.testset_name === '汇总'">
              <span class="setting-data">{{ scope.row.testset_name }}</span>
            </template>
            <el-button v-else size="mini" type="primary" round @click="summarylog(scope.row)">{{ scope.row.testset_name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="executor_name"
          label="执行机"
          align="center"
          sortable
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="case_count"
          label="用例总数"
          align="center"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag size="small" type="warning">{{ scope.row.case_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="case_executed_count"
          label="已执行数"
          align="center"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag size="small">{{ scope.row.case_executed_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="case_success_count"
          label="成功数"
          align="center"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag size="small" type="success">{{ scope.row.case_success_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="case_failed_count"
          label="	失败数"
          align="center"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag size="small" type="danger">{{ scope.row.case_success_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="	状态"
          align="center"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 'completed'" size="small" type="success">执行完成</el-tag>
            <el-tag v-if="scope.row.status === 'stopped'" size="small" type="danger">已停止</el-tag>
            <el-tag v-if="scope.row.status === 'wait'" size="small">等待执行</el-tag>
            <el-tag v-if="scope.row.status === 'hang'" size="small" type="warning">悬挂</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="测试日志" width="70%" :visible.sync="testlogvisible">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>充值和余量查询</span>
        </div>
        <div>
          <p v-for="( item ) in testsetLogs " style="font-weight:bold;">{{ item }} </p>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>
<script>
import Vue from 'vue'
import mixinBaseView from '@/mixins/view-base.js'
import { testtaskList, deltesttask, SummaryList, testsetLog, timesetLog, jobtestreport, stopTask } from '@/api/testtask'
export default {
  mixins: [mixinBaseView],
  data() {
    return {
      jobid: '',
      timer: '',
      currentTaskName: '脚本调试',
      startbutton: 1,
      // 日志弹出框
      testlogvisible: false,
      testsetLogs: [],
      // 设置名称
      commonPageSetting: {
        entityTitle: '该测试任务' // 当前页面的对象名称
      },
      summaryvisible: false,
      // 搜索条件
      dataForm: {
        demoname: ''
      },
      // 表单数据
      tableData: [],
      // 汇总
      SummaryData: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      totalPage: 0
    }
  },
  computed: {
    // 总数
    total() {
      return this.tableData.length
    },
    // 当前分页数据
    pageData() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  mounted() {
    this.getData()
  },
  methods: {
    // 表格排序
    tableSortChange({ column, prop, order }) {
      if (order === null) {
        this.handleFilter()
        return false
      }
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    // 条件查询
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = this.selfHandleFilter(data)
    },
    // 详细的过滤操作，需要覆写此方法
    selfHandleFilter(data) {
      if (this.dataForm.demoname !== '') {
        data = data.filter(item => item.job_name.indexOf(this.dataForm.demoname) !== -1)
      }
      if (this.dataForm.demoname === '') {
        this.getData()
      }
      return data
    },
    selectRowHandle(selection) {
      this.selectIds = []
      this.selectmapIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectmapIds.push(row.map_id)
        self.selectIds.push(row.id)
      })
    },
    // 获取数据
    getData() {
      const params = {}
      testtaskList(params).then(response => {
        this.tableData = response.data.reverse()
        for (var i = 0; i < this.tableData.length; i++) {
          Vue.set(this.tableData[i], 'testing_progress', parseInt(this.tableData[i].case_executed_count / this.tableData[i].case_count * 100))
        }
      })
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 删除
    deleteHandle(row) {
      this.$confirm('是否删除' + this.commonPageSetting.entityTitle + ' 【' + row.job_name + '】 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deltesttask({ id: row.id }).then(response => {
          this.getData()
          this.$message.success('删除成功')
        })
      }).catch(() => {
      })
    },
    // 批量操作
    batchHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      let successCount = 0
      let failCount = 0
      const self = this
      this.$confirm('是否批量删除选择的共 ' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectIds.forEach(function(val) {
          deltesttask({ id: val }).then(response => {
            successCount++
          }).catch(() => {
            failCount++
          })
        })

        const intervalId = setInterval(function() {
          if ((successCount + failCount) === self.selectIds.length) {
            clearInterval(intervalId)
            self.getData()
            self.$alert('本次共删除成功 ' + successCount + ' 条数据, 删除失败 ' + failCount + ' 条数据!', '提示')
          }
        }, 300)
      }).catch()
    },
    // 导出
    exportexcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')

        const tHeader = ['序号', '任务名称', '执行机/组', '开始时间', '结束时间', '创建人', '任务状态', '总用例数', '已执行数', '成功数', '失败数', '测试进度', '操作']// 上面设置Excel的表格第一行的标题

        const filterVal = ['id', 'job_name', 'executor_name', 'start_time', 'completed_time', 'creator_name', 'status', 'case_count', 'case_executed_count', 'case_success_count', 'case_failed_count', 'testing_progress'] // 上面的index、nickName、name是tableData里对象的属性

        const list = this.tableData // 把data里的tableData存到list

        for (var i = 0; i < list.length; i++) {
          if (list[i].executor_name === '') {
            list[i].executor_name = list[i].executor_group_name
          }
          if (list[i].status === 'completed') {
            list[i].status = '执行完成'
          } else if (list[i].status === 'stopped') {
            list[i].status = '已停止'
          } else if (list[i].status === 'wait') {
            list[i].status = '等待'
          }
          list[i].testing_progress = list[i].testing_progress + '%'
        }
        const data = this.formatJson(filterVal, list)

        export_json_to_excel(tHeader, data, '测试任务') // 标题，数据，文件名
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 汇总信息
    summary(row) {
      this.currentTaskName = row.job_name
      this.startbutton = 1
      var case_count = 0
      var case_executed_count = 0
      var case_success_count = 0
      var case_failed_count = 0
      this.jobid = row.id
      SummaryList({ job_id: row.id }).then(response => {
        this.SummaryData = response.data.reverse()
        for (var i = 0; i < this.SummaryData.length; i++) {
          if (this.SummaryData[i].executor_name === '') {
            this.SummaryData[i].executor_name = this.SummaryData[i].executor_group_name
          }
          case_count = case_count + this.SummaryData[i].case_count
          case_executed_count = case_executed_count + this.SummaryData[i].case_executed_count
          case_success_count = case_success_count + this.SummaryData[i].case_success_count
          case_failed_count = case_failed_count + this.SummaryData[i].case_failed_count
        }
        this.SummaryData.push({
          testset_name: '汇总',
          executor_name: '',
          case_count: case_count,
          case_executed_count: case_executed_count,
          case_success_count: case_success_count,
          case_failed_count: case_failed_count,
          status: ''
        })
        this.summaryvisible = true
      })
    },
    // 打开日志调试界面
    summarylog(row) {
      this.testlogvisible = true
      testsetLog({ result_set_id: row.result_set_id }).then(response => {
        this.testsetLogs = response.data
        if (this.testsetLogs.length === 0) {
          this.testsetLogs.push('暂无数据')
        }
      })
    },
    // 开启||关闭
    openrefresh() {
      this.startbutton = 0
      this.timer = setInterval(() => {
        timesetLog({ job_id: this.jobid }).then(response => {
        })
      }, 2000)
    },
    closerefresh() {
      this.startbutton = 1
      clearInterval(this.timer)
    },
    closesummarylog() {
      clearInterval(this.timer)
    },
    testreport(row) {
      jobtestreport({ job_id: row.id }).then(response => {
        window.open(process.env.VUE_APP_BASE_API + '/' + response.data)
      })
    },
    stopTask(row) {
      stopJob({job_id: row.id}).then(response => {})
    }
  }

}
</script>

<style scoped>

</style>
